// packageFT/guide/application/application.js
const app = getApp()
import WxValidate from '../../../utils/WxValidate'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    formData: {
      realname: '',
      mobile: '',
      service_years: 1,
      guideLevel: '初级导游',
      province_id: '',
      city_id: '',
      district_id: '',
      registerAreaValue: '',
      registerAreaText: '',
      responsibleArea: [],
      region: [],
      Introduction: '',
      capability_certificate: [],
      id_card_front: [],
      id_card_reverse: []
    },
    can_apply: false,
    registerAreaOptions: [],
    responsibleAreaOptions: [],
    registerAreaShow: false,
    responsibleAreaShow: false,
    pageType: '',
    btnLock: false,
    readonly: false,
    recommendInfo: {
      id: '',
      store_name: '',
      is_exist_recommend: 0
    },
    referenceShow: false,
    selectedUserId: ''
  },

  /**
   * 数据双向绑定
   * @param {Object} e 
   */
  updateFormData: function(e) {
    const { formdatakey } = e.currentTarget.dataset
    const value = e.detail
    const key = 'formData.' + [formdatakey]
    this.setData({
      [key]: value 
    })
  },

  /**
   * 显示/隐藏弹窗
   * @param {Object} e 
   */
  popupToggle: function(e) {
    const { readonly } = this.data
    if (readonly) return
    const { text, show } = e.currentTarget.dataset
    this.setData({
      [text]: show
    })
  },

  /**
   * 负责区域选择确认
   * @param {Object} e 
   */
  responsibleAreaFinish: function(e) {
    const {selectedOptions, tabIndex, value } = e.detail
    if (tabIndex == 1) {
      let { responsibleArea, region } = this.data.formData
      if (responsibleArea.length >= 20) {
        app.tips('最多选择20个')
        return
      }
      const index = responsibleArea.findIndex(item => item.value == value)
      // 已存在
      if (index > -1) {
        app.tips(`已选择【${selectedOptions[1].text}】`)
        return
      }
      responsibleArea.push({
        text: selectedOptions[0].text + '-' + selectedOptions[1].text,
        value
      })
      region.push({
        province_id: selectedOptions[0].value,
        city_id: selectedOptions[1].value
      })
      this.setData({
        'formData.responsibleArea': responsibleArea,
        'formData.region': region,
        responsibleAreaShow: false
      })
    }
  },

  /**
   * 删除选中的负责区域
   * @param {Object} e 
   */
  delResponsibleArea: function(e) {
    const { readonly, formData } = this.data
    if (readonly) return
    const { value } = e.target.dataset
    let { responsibleArea, region } = formData
    let index = responsibleArea.findIndex(item => item.value == value)
    let index1 = region.findIndex(item => item.city_id == value)
    responsibleArea.splice(index, 1)
    region.splice(index1, 1)
    this.setData({
      'formData.responsibleArea': responsibleArea,
      'formData.region': region
    })
  },

  /**
   * 注册区域选择确认
   * @param {Object} e 
   */
  registerAreaFinish: function(e) {
    const { selectedOptions, value } = e.detail;
    const fieldValue =`${selectedOptions[0].text}-${selectedOptions[1].text}-${selectedOptions[2].text}` 
    this.setData({
      'formData.registerAreaText': fieldValue,
      'formData.province_id': selectedOptions[0].value,
      'formData.city_id': selectedOptions[1].value,
      'formData.district_id': selectedOptions[2].value,
      'formData.registerAreaValue': selectedOptions[2].value,
      registerAreaShow: false
    })
  },

  /**
   * 编辑导游信息
   */
  editForm: function() {
    const { readonly } = this.data
    if (readonly) {
      this.validateUpdate()
    } else {
      this.submitForm()
    }
  },

  /**
   * 验证导游修改申请
   */
  validateUpdate: function() {
    const urlStr = app.getNetAddresss('plugin.guide.frontend.apply.validateUpdate')
    const _this = this
    wx.showLoading({ title: '验证中...' })
    this.setData({ btnLock: true })
    app._getNetWork({
      url: urlStr,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          const { can_edit_apply, message } = resData.data
          if (can_edit_apply) {
            _this.setData({ readonly: false })
            wx.setNavigationBarTitle({
              title: '编辑资料',
            })
          } else {
            wx.showModal({
              title: '提示',
              content: message,
              showCancel: false
            })
          }
        } else {
          app.tips(resData.msg || '验证失败！')
        }
      },
      complete: function() {
        wx.hideLoading()
        _this.setData({ btnLock: false })
      }
    })
  },

  /**
   * 提交申请
   */
  submitForm: function() {
    if (!this.WxValidate.checkForm(this.data.formData)) {
      const error = this.WxValidate.errorList[0]
      app.tips(error.msg)
      return
    }
    const {
      realname,
      mobile,
      service_years,
      province_id,
      city_id,
      district_id,
      region,
      Introduction,
      capability_certificate,
      id_card_front,
      id_card_reverse
    } = this.data.formData
    let data = {
      realname,
      mobile,
      service_years,
      province_id,
      city_id,
      district_id,
      region,
      Introduction,
      annex_file: {
        capability_certificate: capability_certificate[0]?.url,
        id_card_front: id_card_front[0]?.url,
        id_card_reverse: id_card_reverse[0]?.url
      }
    }
    const { id } = this.data.recommendInfo
    if (id) {
      data.recommend_id = id
    }
    const { pageType } = this.data
    let urlStr = ''
    if (pageType == 'edit') {
      urlStr = app.getNetAddresss('plugin.guide.frontend.apply.update')
    } else if (pageType == 'add') {
      urlStr = app.getNetAddresss('plugin.guide.frontend.apply.index')
    } else {
      app.tips('地址有误！')
      return
    }
    wx.showLoading({
      title: '数据提交中...',
    })
    this.setData({ btnLock: true })
    const _this = this
    app._postNetWork({
      url: urlStr,
      data,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          wx.showModal({
            title: '成功',
            content: '信息已提交，等待审核...',
            showCancel: false,
            complete: (resC) => {
              if (resC.confirm) {
                const { tmplIds } = app.data
                wx.requestSubscribeMessage({
                  tmplIds: tmplIds[1],
                  complete: function() {
                    wx.navigateBack({ delta: -1 })
                  }
                })
              }
            }
          })
        } else {
          app.tips(resData.msg || '返回错误！')
        }
      },
      complete: function() {
        wx.hideLoading()
        _this.setData({ btnLock: false })
      }
    })
  },

  /**
   * 图片选中上传(多图)
   * @param {Object} e 
   */
  afterRead: function(e) {
    const { file = [] } = e.detail
    let promiseArray = []
    const uploaderUrl = app.getNetAddresss(app.data.uploaderPicUrl)
    wx.showLoading({
      title: '上传中',
    })
    file.forEach(item => {
      promiseArray.push(new Promise((resolve, reject) => {
        wx.uploadFile({
          filePath: item.url,
          name: 'file',
          url: uploaderUrl,
          success: function(res) {
            resolve(res)
          },
          fail: function(err) {
            reject(err)
          }
        })
      }))
    })
    Promise.all(promiseArray).then(resArray => {
      wx.hideLoading()
      const addUrlArray = resArray.map(item => {
        const resData = JSON.parse(item.data)
        return {url: resData.data.img_url}
      })
      const { formData } = this.data
      const { field } = e.currentTarget.dataset
      const currentImgUrls = [...this.data.formData[field], ...addUrlArray]
      formData[field] = currentImgUrls
      this.setData({ formData })
    }).catch(err => {
      wx.hideLoading()
    })
  },

  /**
   * 删除已上传的图片
   * @param {Object} e 
   */
  deleteFile: function(e) {
    const { readonly, formData } = this.data
    if (readonly) return
    const { index } = e.detail
    const { field } = e.currentTarget.dataset
    let currentData = formData[field]
    const key = `formData.${field}`
    currentData.splice(index, 1)
    this.setData({
      [key]: currentData
    })
  },

  /**
   * 获取省市列表(出行城市)
   */
  getAddress: function() {
    wx.showLoading({
      title: '加载中...',
    })
    const _this = this
    let urlStr = app.getNetAddresss("member.member-address.address");
    app._postNetWork({
      url: urlStr,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          const thirdLevelRegion = resData.data.province.map(item => {
            const child = resData.data.city.filter(item1 => item1.parentid == item.id).map(item1 => {
              const child2 = resData.data.district.filter(item2 => item2.parentid == item1.id).map(item2 => {
                return {
                  text: item2.areaname,
                  value: item2.id + ''
                }
              })
              return {
                text: item1.areaname,
                value: item1.id + '',
                children: child2
              }
            })
            return {
              text: item.areaname,
              value: item.id + '',
              children: child
            }
          })
          const secondaryRegion = resData.data.province.map(item => {
            const child = resData.data.city.filter(item1 => item1.parentid == item.id).map(item1 => {
              return {
                text: item1.areaname,
                value: item1.id + ''
              }
            })
            return {
              text: item.areaname,
              value: item.id + '',
              children: child
            }
          })
          _this.setData({ 
            registerAreaOptions: thirdLevelRegion,
            responsibleAreaOptions: secondaryRegion
          })
        } else {
          app.tips(resData.msg)
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 表单验证
   */
  initValidate: function() {
    const rules = {
      realname: {
        required: true
      },
      mobile: {
        required: true,
        tel: true
      },
      registerAreaValue: {
        required: true
      },
      responsibleArea: {
        isEmptyArray: true
      },
      Introduction: {
        required: true
      },
      capability_certificate: {
        isEmptyArray: true
      },
      id_card_front: {
        isEmptyArray: true
      },
      id_card_reverse: {
        isEmptyArray: true
      }
    }
    const message = {
      realname: {
        required: '请输入姓名'
      },
      mobile: {
        required: '请输入手机号',
        tel: '请输入正确的手机号码'
      },
      registerAreaValue: {
        required: '请选择注册区域'
      },
      responsibleArea: {
        isEmptyArray: '请选择负责区域'
      },
      Introduction: {
        required: '请填写个人简介'
      },
      capability_certificate: {
        isEmptyArray: '请上传导游证件'
      },
      id_card_front: {
        isEmptyArray: '请上传身份证人像面'
      },
      id_card_reverse: {
        isEmptyArray: '请上传身份证国徽面'
      }
    }
    this.WxValidate = new WxValidate(rules, message)
    this.WxValidate.addMethod('isEmptyArray', (value) => {
      return value.length > 0
    })
  },

  /**
   * 根据参数页面类型设置不同显示
   * @param {Object} options 
   */
  setPageInfo: function(options) {
    this.setData({
      pageType: options?.pageType || ''
    })
    const { pageType } = options
    if (pageType && pageType == 'add') {
      this.isCanApply()
      wx.setNavigationBarTitle({
        title: '导游申请',
      })
    } else if (pageType && pageType == 'edit') {
      this.getGuideInfo()
      wx.setNavigationBarTitle({
        title: '我的资料',
      })
      this.setData({ readonly: true })
    }
  },

  /**
   * 编辑时获取导游信息
   */
  getGuideInfo: function() {
    const _this = this
    const urlStr = app.getNetAddresss("plugin.guide.frontend.guide.detail")
    wx.showLoading({
      title: '加载中...',
    })
    app._getNetWork({
      url: urlStr,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          _this.rewriteFormData(resData.data)
        } else {
          app.tips(resData.msg)
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },
  
  /**
   * 检查是否可申请导游
   */
  isCanApply: function() {
    const _this = this
    const urlStr = app.getNetAddresss('plugin.guide.frontend.apply.detail')
    wx.showLoading({
      title: '加载中...',
    })
    app._postNetWork({
      url: urlStr,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          const { can_apply } = resData.data
          if (can_apply == 99) {
            _this.setData({ can_apply: true })
          } else {
            wx.showModal({
              title: '提示',
              content: '信息审核中...', // resData.msg || '不可申请',
              showCancel: false,
              complete: (res) => {
                if (res.confirm) {
                  wx.navigateBack({ delta: -1 })
                }
              }
            })
            // 回写表单数据
            _this.rewriteFormData(resData.data)
          }
        } else {
          app.tips(resData.msg || '请求错误！')
        }
      },
      complete: function(err) {
        wx.hideLoading()
      }
    })
  },

  /**
   * 回写表单数据
   * @param {Object} data 数据内容
   */
  rewriteFormData: function(data) {
    const { pageType } = this.data
    this.setData({
      'formData.realname': data.realname || '',
      'formData.mobile': data.mobile || '',
      'formData.service_years': data.service_years,
      'formData.registerAreaText': `${data.province_name}-${data.city_name}-${data.district_name}` ,
      'formData.registerAreaValue': data.district_id || '',
      'formData.Introduction': data.Introduction || '',
      'formData.province_id': data.province_id,
      'formData.city_id': data.city_id,
      'formData.district_id': data.district_id
    })
    if (pageType == 'edit') {
      // 负责区域
      let responsibleArea = []
      let region = []
      const regionList = data.has_many_region || []
      regionList.forEach(item => {
        responsibleArea.push({
          text: item.province_name + '-' + item.city_name,
          value: item.city_id
        })
        region.push({
          province_id: item.province_id,
          city_id: item.city_id
        })
      })
      this.setData({
        'formData.guideLevel': data?.has_one_level?.name || '初级导游',
        'formData.responsibleArea': responsibleArea,
        'formData.region': region
      })
    }
    if (data.annex_file && data.annex_file.capability_certificate) {
      this.setData({
        'formData.capability_certificate': [{
          url: data.annex_file.capability_certificate
        }]
      })
    }
    if (data.annex_file && data.annex_file.id_card_front) {
      this.setData({
        'formData.id_card_front': [{
          url: data.annex_file.id_card_front
        }]
      })
    }
    if (data.annex_file && data.annex_file.id_card_reverse) {
      this.setData({
        'formData.id_card_reverse': [{
          url: data.annex_file.id_card_reverse
        }]
      })
    }
    if (data.has_one_recommend) {
      this.setData({
        recommendInfo: {
          id: data.has_one_recommend.id,
          store_name: data.has_one_recommend.store_name,
          is_exist_recommend: 1
        }
      })
    }
  },

  /**
   * 显示推荐人弹窗
   */
  showReference() {
    const { readonly, recommendInfo, pageType } = this.data
    const { is_exist_recommend } = recommendInfo
    // 已存在推荐人 || 非编辑状态
    if ((pageType == 'edit' && is_exist_recommend) || readonly) return
    this.setData({
      referenceShow: true
    });
  },

  /**
   * 隐藏推荐人弹窗
   */
  hideReference() {
    this.setData({
      referenceShow: false
    })
  },

  /**
   * 选中推荐人
   * @param {Object} e 
   */
  seleceUser(e) {
    const { detail } = e
    this.setData({
      recommendInfo: {
        id: detail.id,
        store_name: detail.name
      },
      selectedUserId: detail.id,
      referenceShow: false
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setPageInfo(options)
    this.initValidate()
    this.getAddress()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})